package tuling.netty.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author RenGaoshuai
 * @date 2023/11/20 14:05
 * @description AIO有难度，全部是基于回调完成的，每个步骤都是一个线程在处理
 *
 * 还有一个问题，为什么netty不在java aio的基础上封装呢？
 * netty不看重windows环境的使用
 * linux环境中aio在底层上还是使用的epoll模型，别没有很大的改善，并且aio还处于发展中，与其使用这种不确定的，还不如使用稳定的nio。
 *
 */
public class AioServer {

    public static void main(String[] args) throws IOException {
        final AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(9000));

        serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel socketChannel, Object attachment) {
                try {
                    System.out.println("2‐‐"+Thread.currentThread().getName());
                     // 再此接收客户端连接，如果不写这行代码后面的客户端连接连不上服务端
                     serverChannel.accept(attachment, this);
                     System.out.println(socketChannel.getRemoteAddress());
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    socketChannel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                        @Override
                        public void completed(Integer result, ByteBuffer attachment) {
                            System.out.println("3‐‐"+Thread.currentThread().getName());
                             buffer.flip();
                             System.out.println(new String(buffer.array(), 0, result));
                             socketChannel.write(ByteBuffer.wrap("HelloClient".getBytes()));
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                            exc.printStackTrace();
                        }
                    });
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });

        System.out.println("1‐‐"+Thread.currentThread().getName());
    }
}
